const user = require('../models/sys_user')
const jwt  = require('jsonwebtoken')
const bctypt = require('bcryptjs')

// 登陆
const login = async function(ctx) {
  const data = ctx.request.body
  const userInfo = await user.login(data)
  console.log(userInfo)
  console.log(data)
  if(userInfo!= null) {   //用户名不为空
    if(data.password!==userInfo.password) {  //密码错误
      ctx.body = {
        success: false,
        message: '密码错误'
      }
    }else {   //密码正确
      const userToken = {
        name: userInfo.name,
        id: userInfo.id
        
      }
      const secret = 'vue-campus'
      const token = jwt.sign(userToken, secret)   //签发token
      ctx.body = {
        success: true,
        data: {
          token: token
        }
        
      }
    }
  }else {
    ctx.body = {
      success: false,
      message: '用户不存在'
    }
  }
}
// 获取用户信息
const getInfo = async function(data) {
  const userInfo = user.getInfo(data)
  return userInfo
}
// 注册
const register = async function(ctx) {
  const salt = bctypt.genSaltSync(10)
  const hash = bctypt.hashSync(ctx.request.body.password, salt)
  const data = {
    name: ctx.request.body.name,
    password: hash
  }
  const result = await user.register(data)
  ctx.body = {
    success: true
  }
}

module.exports = {
  login,
  register,
  getInfo
}